package com.yanchengtect.demo.progress.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.yanchengtect.demo.progress.utils.ResultUtils;


/**
* @author 文心雕龙 Email：xuwenlong@shike8888.com
* @version 创建时间：2018年8月30日 上午11:20:57
* 类说明
*/
@Service
public class ProgressService {
	
	private static Logger log = Logger.getLogger(ProgressService.class);
	
	@Resource
	private RedisTemplate<String, Map<String, String>> redisTemplate;
	

	/**
	 * 进度条的启动类
	 * @param key 进度条进程的标志(唯一)
	 */
	public void start(String key) {
		ValueOperations<String, Map<String, String>> opsForValue = redisTemplate.opsForValue();
		Map<String, String> map = opsForValue.get(key);
		if (null!=map ) {
			System.out.println("进程正在进行中");
		}else {
			
			int length = 1163;
			//初始化进度
			Map<String, String> value = new HashMap<String, String>();
			value.put("total", length+"");
			value.put("oped", "0");
			value.put("status", "进行中");
			
			// 初始化数据存进redis中
			opsForValue.set(key, value);
			log.info("进程开始");
			doProgress2(key,length,100);
		}
	}
	
	
	
	/**
	 * 根据每次条数来进行进度条的更新,前端进行进度条百分比的计算
	 * @param length 总条数
	 * @param count 每次处理的条数 
	 */
	private void doProgress2(String key,int length,int count) {
		
		ValueOperations<String, Map<String, String>> opsForValue = redisTemplate.opsForValue();
		Map<String, String> map = opsForValue.get(key);
		
		if (null == map) {
			map = new HashMap<String, String>();
			map.put("oped", "0");
		}
		
		if (length>count) {
			
			int times =(int) length/count+1;
			log.info("此次共有"+times+"批次处理");
			for (int i = 0; i <times; i++) {
				log.info("第"+(i+1)+"批处理");
				
				int start = i*count; 								// 开始的记录数
				int end = (i+1)*count>length?length:((i+1)*count); 	// 结束的记录数
				log.info("此次处理的范围是:"+start+"到"+end);
				
				for (int j = start; j < end; j++) {
					// 处理逻辑
					try {
						log.info("当前处理的记录编号是:"+j);
						Thread.sleep(10);
					} catch (Exception e) {
						log.info("线程异常");
					}
				}
				
				// 更新redis中进度
				map.put("oped", end+"");
				if (end == length) {
					map.put("status", "已完成");
					log.info("进程完成");
				}
				opsForValue.set(key,map);
			}
		}else {
			// 更新redis中进度
			map.put("oped", ""+length);
			map.put("status", "已完成");
			log.info("进程完成");
			opsForValue.set(key,map);
		}
	}


	/**
	 * 根据tokenkey获取进程的进度
	 * @param key tokenkey
	 * @return 进度结果
	 */
	public String getProgress(String key) {
		ValueOperations<String, Map<String, String>> opsForValue = redisTemplate.opsForValue();
		Map<String, String> map = opsForValue.get(key);
		if (null == map) {
			return ResultUtils.error(0, "没有该进程");
		}
		
		return ResultUtils.success(map);
	}
	 
	
}
